//
//  TaskEditionViewController.m
//  MemoryTasks
//
//  Created by Philippe Bouamriou on 13/05/10.
//  Copyright 2010 Philippe Bouamriou. All rights reserved.
//

#import "TaskEditionViewController.h"
#import "CellViewControllerForLabelAndTextField.h"
#import "CellViewControllerForTwoLabels.h"
#import "CellViewControllerForThreeLabels.h"
#import "CellViewControllerForLabelAndSwitch.h"
#import "DateAndTimeSelectionViewController.h"
#import "CategoriesViewController.h"
#import "Category.h"


#pragma mark Private Methods definition

// Private Methods
@interface TaskEditionViewController ()
// Actions
- (void)doneButtonPressed;

// Custom methods
- (void)resignFirstResponderForAllControls;
- (BOOL)checkValidityAndUpdateButtonDoneState;
- (BOOL)checkValidityForLabelAndTextFieldCell:(CellViewControllerForLabelAndTextField*)cellCtrl;
- (BOOL)checkValidityForTwoLabelsCell:(CellViewControllerForTwoLabels*)cellCtrl;
- (void)updateIndexPathForSection:(NSUInteger)section;
- (void)updateIndexPathForSection:(NSUInteger)section fromRow:(NSUInteger)row;
- (NSDate *)getMaximumDate;

@property (nonatomic, strong) CellViewControllerForThreeLabels *_startDateCellViewCtrl;
@property (nonatomic, strong) CellViewControllerForThreeLabels *_endDateCellViewCtrl;
@property (nonatomic, strong) CellViewControllerForThreeLabels *_endDateEstimatedCellViewCtrl;

@end

#pragma mark -
#pragma mark Implementation

@implementation TaskEditionViewController

@synthesize navController, tableView, doneButton;
@synthesize _startDateCellViewCtrl, _endDateCellViewCtrl, _endDateEstimatedCellViewCtrl;

/*
 // The designated initializer.  Override if you create the controller programmatically and 
 // want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
   
   // Title
   
   self.title = NSLocalizedString(@"Task creation", @"Window Title : Task creation"); 
   
   // Add button in NavigationBar
   
   UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] 
                                     initWithBarButtonSystemItem:UIBarButtonSystemItemDone 
                                     target:self action:@selector(doneButtonPressed)];
   
   self.navigationItem.rightBarButtonItem=barButtonItem;
   doneButton = barButtonItem;
   doneButton.enabled = NO;
    
   // SECTION CREATION
   // *** SECTION *** Task name & description *************************************************************************
   
   NSMutableArray *arraySectionTaskName = [[NSMutableArray alloc] init];
   
    // *** ROW *** Task Name
   
   CellViewControllerForLabelAndTextField *cellNameCtrl = [[CellViewControllerForLabelAndTextField alloc] 
                                                           initWithNibName:@"CellViewControllerForLabelAndTextField" 
                                                           bundle:nil];
   cellNameCtrl.identifier = kCellIdTaskName;
   cellNameCtrl.labelText = NSLocalizedString(@"Name", @"Name edition label");
   cellNameCtrl.indicationText = NSLocalizedString(@"Tap here to edit the name",
                                                   @"Placeholder of the name field");
   cellNameCtrl.delegate = self;
   [arraySectionTaskName addObject:cellNameCtrl];
   
    // *** ROW *** Comment
   
   CellViewControllerForLabelAndTextField *cellCommentCtrl = [[CellViewControllerForLabelAndTextField alloc] 
                                                              initWithNibName:@"CellViewControllerForLabelAndTextField" 
                                                              bundle:nil];

   cellCommentCtrl.identifier = kCellIdComment;
   cellCommentCtrl.labelText = NSLocalizedString(@"Comment", @"Comment edition label");
   cellCommentCtrl.indicationText = NSLocalizedString(@"Tap here to edit the comment",
                                                   @"Placeholder of the comment field");
   
   [arraySectionTaskName addObject:cellCommentCtrl];
   
   
   // *** SECTION *** Dates *******************************************************************************************
   
   NSMutableArray *arraySectionDates = [[NSMutableArray alloc] init];
   
   // *** ROW *** Start Date
   
   CellViewControllerForThreeLabels *cellStartDateCtrl = [[CellViewControllerForThreeLabels alloc]
                                                        initWithNibName:@"CellViewControllerForThreeLabels"
                                                        bundle:nil];
      
   cellStartDateCtrl.identifier = kCellIdStartDate;
   cellStartDateCtrl.labelText = NSLocalizedString(@"Start date", @"Start date edition label");
   NSDate *currentDate = [NSDate date];
   cellStartDateCtrl.mainValueText = [NSDateFormatter localizedStringFromDate:currentDate 
                                                                dateStyle:NSDateFormatterLongStyle 
                                                                timeStyle:NSDateFormatterNoStyle];
   cellStartDateCtrl.extendedValueText = [NSDateFormatter localizedStringFromDate:currentDate 
                                                                    dateStyle:NSDateFormatterNoStyle 
                                                                    timeStyle:NSDateFormatterShortStyle];
   cellStartDateCtrl.value = currentDate;
   
   [arraySectionDates addObject:cellStartDateCtrl];
   self._startDateCellViewCtrl = cellStartDateCtrl;
   
   // *** ROW *** End Date Known
   
   CellViewControllerForLabelAndSwitch *cellEndDateKnownCtrl = [[CellViewControllerForLabelAndSwitch alloc] 
                                                                initWithNibName:@"CellViewControllerForLabelAndSwitch" 
                                                                bundle:nil];
   cellEndDateKnownCtrl.identifier = kCellIdEndDateKnown;
   cellEndDateKnownCtrl.labelText = NSLocalizedString(@"End date known", @"End date known label");
   cellEndDateKnownCtrl.switchOn = NO;
   cellEndDateKnownCtrl.delegate = self;
   
   [arraySectionDates addObject:cellEndDateKnownCtrl];
   
   // *** ROW *** End Date (HIDDEN)
   
   CellViewControllerForThreeLabels *cellEndDateCtrl = [[CellViewControllerForThreeLabels alloc]
                                                      initWithNibName:@"CellViewControllerForThreeLabels"
                                                      bundle:nil];
   cellEndDateCtrl.identifier = kCellIdEndDate;
   cellEndDateCtrl.labelText = NSLocalizedString(@"End date", @"Start date edition label");
   cellEndDateCtrl.mainValueText = @"";
   cellEndDateCtrl.extendedValueText = @"";
   cellEndDateCtrl.hidden = YES;
   
   cellEndDateKnownCtrl.childViewCells = [NSArray arrayWithObject:cellEndDateCtrl];
   
   [arraySectionDates addObject:cellEndDateCtrl];
   self._endDateCellViewCtrl = cellEndDateCtrl;
   
   // *** ROW *** End Date Estimated Known
   
   CellViewControllerForLabelAndSwitch *cellEndDateEstimatedKnownCtrl = 
          [[CellViewControllerForLabelAndSwitch alloc] initWithNibName:@"CellViewControllerForLabelAndSwitch" 
                                                                bundle:nil];
   
   cellEndDateEstimatedKnownCtrl.identifier = kCellIdEndDateEstimatedKnown;
   cellEndDateEstimatedKnownCtrl.labelText = NSLocalizedString(@"End date estimated known", 
                                                                @"End date estimated known label");
   cellEndDateEstimatedKnownCtrl.switchOn = NO;
   cellEndDateEstimatedKnownCtrl.delegate = self;
   cellEndDateEstimatedKnownCtrl.linkedCell = cellEndDateKnownCtrl;
   cellEndDateKnownCtrl.linkedCell = cellEndDateEstimatedKnownCtrl;
   
   [arraySectionDates addObject:cellEndDateEstimatedKnownCtrl];
   
   // *** ROW *** End Date Estimated (HIDDEN)
   
   CellViewControllerForThreeLabels *cellEndDateEstimatedCtrl = [[CellViewControllerForThreeLabels alloc]
                                                               initWithNibName:@"CellViewControllerForThreeLabels"
                                                               bundle:nil];
   cellEndDateEstimatedCtrl.identifier = kCellIdEndDateEstimated;
   cellEndDateEstimatedCtrl.labelText = NSLocalizedString(@"End date estimated", @"End date estimated edition label");
   cellEndDateEstimatedCtrl.mainValueText = @"";
   cellEndDateEstimatedCtrl.extendedValueText = @"";
   cellEndDateEstimatedCtrl.hidden = YES;
   
   [arraySectionDates addObject:cellEndDateEstimatedCtrl];
   self._endDateEstimatedCellViewCtrl = cellEndDateEstimatedCtrl;
   
   // *** ROW *** End Date Estimated (HIDDEN)
   
   CellViewControllerForLabelAndSwitch *cellAlarmActivatedCtrl = 
         [[CellViewControllerForLabelAndSwitch alloc] initWithNibName:@"CellViewControllerForLabelAndSwitch" 
                                                               bundle:nil];
   
   cellAlarmActivatedCtrl.identifier = kCellIdEndDateAlarm;
   cellAlarmActivatedCtrl.labelText = NSLocalizedString(@"Alarm activated", 
                                                     @"Alarm activated label");
   cellAlarmActivatedCtrl.switchOn = YES;
   cellAlarmActivatedCtrl.delegate = self;
   cellAlarmActivatedCtrl.hidden = YES;
   
   cellEndDateEstimatedKnownCtrl.childViewCells = [NSArray arrayWithObjects:cellEndDateEstimatedCtrl, 
                                                   cellAlarmActivatedCtrl,
                                                   nil];
   
   [arraySectionDates addObject:cellAlarmActivatedCtrl];
   
   
   // *** SECTION *** Category ****************************************************************************************
   
   NSMutableArray *arraySectionCategory = [[NSMutableArray alloc] init];
   
   // *** ROW *** Category
   
   CellViewControllerForTwoLabels *cellCategoryCtrl = [[CellViewControllerForTwoLabels alloc]
                                                       initWithNibName:@"CellViewControllerForTwoLabels"
                                                       bundle:nil];
   cellCategoryCtrl.identifier = kCellIdCategory;
   cellCategoryCtrl.labelText = NSLocalizedString(@"Category", @"category edition label");
   cellCategoryCtrl.valueText = @"";
   
   [arraySectionCategory addObject:cellCategoryCtrl];
   
   // *** ROW *** Sub Category Enabled (HIDDEN)
   
   CellViewControllerForLabelAndSwitch *cellSubCategoryEnableCtrl = 
   [[CellViewControllerForLabelAndSwitch alloc] initWithNibName:@"CellViewControllerForLabelAndSwitch" 
                                                         bundle:nil];
   
   cellSubCategoryEnableCtrl.identifier = kCellIdSubCategoryEnable;
   cellSubCategoryEnableCtrl.labelText = NSLocalizedString(@"Sub category", 
                                                           @"Sub category label");
   cellSubCategoryEnableCtrl.switchOn = NO;
   cellSubCategoryEnableCtrl.delegate = self;
   cellSubCategoryEnableCtrl.linkedCell = nil;
   cellSubCategoryEnableCtrl.hidden = YES;
   cellCategoryCtrl.linkedCell = cellSubCategoryEnableCtrl;
   
   [arraySectionCategory addObject:cellSubCategoryEnableCtrl];
   
   
   // *** ROW *** Sub Category (HIDDEN)
   
   CellViewControllerForTwoLabels *cellSubCategoryCtrl = [[CellViewControllerForTwoLabels alloc]
                                                       initWithNibName:@"CellViewControllerForTwoLabels"
                                                       bundle:nil];
   cellSubCategoryCtrl.identifier = kCellIdSubCategory;
   cellSubCategoryCtrl.labelText = NSLocalizedString(@"Sub category", @"category edition label");
   cellSubCategoryCtrl.valueText = @"";
   cellSubCategoryCtrl.hidden = YES;
   
   [arraySectionCategory addObject:cellSubCategoryCtrl];
   
   //******************************************************************************************************************
   // Build sections, sectionNames, localSectionNames
   
   sections = [[NSDictionary alloc] initWithObjectsAndKeys:arraySectionTaskName, kSectionTaskNameKey, 
               arraySectionDates, kSectionDatesKey, arraySectionCategory, kSectionCategoryKey, nil];
   
   sectionNames = [[NSArray alloc] initWithObjects:kSectionTaskNameKey, kSectionDatesKey, kSectionCategoryKey,nil];
   
   localSectionNames = [[NSArray alloc] initWithObjects:NSLocalizedString(@"Task name & description", 
                                                                          @"Title for label task name and description"),
                        NSLocalizedString(@"Dates", @"Title for label title in task edition"),
                        NSLocalizedString(@"Category & Subcategory", @"Title for label title in task edition"),
                        nil];
   
   //******************************************************************************************************************
   // Initialize fieldValues Array
   fieldValues = [[NSMutableArray alloc] initWithCapacity:kNumberOfFieldValues];
   [super viewDidLoad];
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
   [super viewDidUnload];
   // Release any retained subviews of the main view.
   // e.g. self.myOutlet = nil;
   self.navController = nil;
   self.doneButton = nil;
   self.tableView = nil;
   localSectionNames = nil;
   sections = nil;
   sectionNames = nil;
}



/*
- (void)viewDidAppear:(BOOL)animated {
   [super viewDidAppear:animated];
   [tableView reloadData];
}
 */

#pragma mark -
#pragma mark Implementation of protocol UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
   return [sectionNames count];
}

- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:(NSInteger)section {
   NSPredicate * predicate = [NSPredicate predicateWithFormat:@"hidden == NO"];
   return [[[sections valueForKey:[sectionNames objectAtIndex:section]] filteredArrayUsingPredicate:predicate] count];
}

- (NSString *)tableView:(UITableView *)theTableView titleForHeaderInSection:(NSInteger)section {
   return [localSectionNames objectAtIndex:section];
}

- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   NSPredicate * predicate = [NSPredicate predicateWithFormat:@"hidden == NO"];
   CustomCellViewController *cellCtrl = [[[sections valueForKey:[sectionNames objectAtIndex:indexPath.section]] 
                                          filteredArrayUsingPredicate:predicate] objectAtIndex:indexPath.row];

   // Memorize the indexPath (usefull later when switch contained in the ViewCell is set to ON or OFF)
   cellCtrl.indexPath = indexPath;
   return (UITableViewCell*)cellCtrl.view;   
}

#pragma mark -
#pragma mark Implementation of protocol UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
   NSPredicate * predicate = [NSPredicate predicateWithFormat:@"hidden == NO"];
   CustomCellViewController *cellCtrl = [[[sections valueForKey:[sectionNames objectAtIndex:indexPath.section]] 
                                          filteredArrayUsingPredicate:predicate] objectAtIndex:indexPath.row];
   CGFloat height = cellCtrl.height;
   
   return height;
}

- (NSIndexPath *)tableView:(UITableView *)theTableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   return indexPath;
}

// Row selection
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   NSPredicate * predicate = [NSPredicate predicateWithFormat:@"hidden == NO"];
   
   id cellCtrl = [[[sections valueForKey:[sectionNames objectAtIndex:indexPath.section]] 
                   filteredArrayUsingPredicate:predicate] objectAtIndex:indexPath.row];
   
   if ([cellCtrl isKindOfClass:[CellViewControllerForLabelAndTextField class]]) {
      CellViewControllerForLabelAndTextField *cellViewCtrlForLabelAndTextField = cellCtrl;
      [cellViewCtrlForLabelAndTextField becomeFirstResponder];
   } else if ([cellCtrl isKindOfClass:[CellViewControllerForLabelAndSwitch class]]) {
      [self resignFirstResponderForAllControls];
   }
   else if ([cellCtrl isKindOfClass:[CellViewControllerForTwoLabels class]]) {
      CellViewControllerForTwoLabels *cellViewControllerForTwoLabels = cellCtrl;
      CategoriesViewController *newViewCtrl = [[CategoriesViewController alloc]
                                               initWithNibName:@"CategoriesViewController" bundle:nil];
      newViewCtrl.navController = navController;
      newViewCtrl.viewMode = kCategoriesViewModeSelection;
      newViewCtrl.identifier = cellViewControllerForTwoLabels.identifier;
      newViewCtrl.delegate = self;
      [navController pushViewController:newViewCtrl animated:YES];
   }
   else if( [cellCtrl isKindOfClass:[CellViewControllerForThreeLabels class]] ) {
      CellViewControllerForThreeLabels *cellViewControllerForThreeLabels = cellCtrl;
      if (cellViewControllerForThreeLabels.identifier == kCellIdStartDate ) {
         [self resignFirstResponderForAllControls];
         DateAndTimeSelectionViewController *dateAndTimeViewCtrl = 
            [[DateAndTimeSelectionViewController alloc]
             initWithNibName:@"DateAndTimeSelectionViewController"
             bundle:nil];
         dateAndTimeViewCtrl.title = NSLocalizedString(@"Start date",
                                                       @"Window title : start date");
         dateAndTimeViewCtrl.date = cellViewControllerForThreeLabels.value;
         dateAndTimeViewCtrl.endDate = [self getMaximumDate];
         dateAndTimeViewCtrl.delegate = self;
         dateAndTimeViewCtrl.identifier = cellViewControllerForThreeLabels.identifier;
         [navController pushViewController:dateAndTimeViewCtrl animated:YES];
      }
      else if (cellViewControllerForThreeLabels.identifier == kCellIdEndDate ) {
         [self resignFirstResponderForAllControls];
         DateAndTimeSelectionViewController *dateAndTimeViewCtrl = 
         [[DateAndTimeSelectionViewController alloc]
          initWithNibName:@"DateAndTimeSelectionViewController"
          bundle:nil];
         dateAndTimeViewCtrl.title = NSLocalizedString(@"End date",
                                                       @"Window title : end date");
         if (cellViewControllerForThreeLabels.value) {
            dateAndTimeViewCtrl.date = cellViewControllerForThreeLabels.value;
         }
         else {
            dateAndTimeViewCtrl.date = [NSDate date];
         }
         
         dateAndTimeViewCtrl.startDate = _startDateCellViewCtrl.value;
         dateAndTimeViewCtrl.delegate = self;
         dateAndTimeViewCtrl.identifier = cellViewControllerForThreeLabels.identifier;
         [navController pushViewController:dateAndTimeViewCtrl animated:YES];
      }
      else if (cellViewControllerForThreeLabels.identifier == kCellIdEndDateEstimated ) {
         [self resignFirstResponderForAllControls];
         DateAndTimeSelectionViewController *dateAndTimeViewCtrl = 
         [[DateAndTimeSelectionViewController alloc]
          initWithNibName:@"DateAndTimeSelectionViewController"
          bundle:nil];
         dateAndTimeViewCtrl.title = NSLocalizedString(@"End date estimated",
                                                       @"Window title : end date estimated");
         if (cellViewControllerForThreeLabels.value) {
            dateAndTimeViewCtrl.date = cellViewControllerForThreeLabels.value;
         }
         else {
            dateAndTimeViewCtrl.date = [NSDate date];
         }
         
         dateAndTimeViewCtrl.startDate = _startDateCellViewCtrl.value;
         dateAndTimeViewCtrl.delegate = self;
         dateAndTimeViewCtrl.identifier = cellViewControllerForThreeLabels.identifier;
         [navController pushViewController:dateAndTimeViewCtrl animated:YES];
      }
      else {
         [self resignFirstResponderForAllControls];
      }
   }
}

#pragma mark -
#pragma mark Implementation of protocol UIViewCellForLabelAndSwitchDelegate

-(void)cellViewController:(CellViewControllerForLabelAndSwitch*)cellViewController 
       switchStateChanged:(UISwitch*)theSwitch {
   
   // Memorise the new value
   NSNumber *number = [[NSNumber alloc] initWithInt:(theSwitch.on == YES)?kSwitchValueOn:kSwitchValueOff];
   cellViewController.value = number;
   
   NSMutableArray *indexPathes = [[NSMutableArray alloc] init];
   NSUInteger nbRowInsertedOrDeleted = 0;
   for(CustomCellViewController *customViewCell in cellViewController.childViewCells) {
      ++nbRowInsertedOrDeleted;
      customViewCell.hidden = theSwitch.on ? NO : YES;
      [indexPathes addObject:[NSIndexPath indexPathForRow:cellViewController.indexPath.row+nbRowInsertedOrDeleted 
                                                inSection:cellViewController.indexPath.section]];
   }
   
   // Rebuild indexPath attribute pour all Cells below the current
   [self updateIndexPathForSection:cellViewController.indexPath.section 
                           fromRow:cellViewController.indexPath.row+1];
      
   
   if (theSwitch.on) {
      // Animate new rows inserted
      if ([indexPathes count] > 0) {
         [tableView insertRowsAtIndexPaths:indexPathes withRowAnimation:UITableViewRowAnimationBottom];
      }
      
      CellViewControllerForLabelAndSwitch *linkedCell = cellViewController.linkedCell;
      
      if (linkedCell != nil) {
         NSMutableArray *anotherIndexPathes = [[NSMutableArray alloc] init];
         if (linkedCell.hidden == NO) {
            linkedCell.hidden = YES;
            [anotherIndexPathes addObject:linkedCell.indexPath];
         }
         
         if (linkedCell.switchOn == YES) {
            NSUInteger row = linkedCell.indexPath.row;
            linkedCell.switchOn = NO;
            for (CustomCellViewController *childViewCell in linkedCell.childViewCells) {
               ++row;
               childViewCell.hidden = YES;
               [anotherIndexPathes addObject:[NSIndexPath indexPathForRow:row 
                                                                inSection:cellViewController.indexPath.section]];
            }
         }
         
         // Animate new rows deleted
         if ([anotherIndexPathes count] > 0) {
            [tableView deleteRowsAtIndexPaths:anotherIndexPathes withRowAnimation:UITableViewRowAnimationTop];
            
            // Rebuild indexPath attribute pour all Cells below the current
            [self updateIndexPathForSection:cellViewController.indexPath.section 
                                    fromRow:linkedCell.indexPath.row];
         }
         
      }
      
   }
   else {
      // Animate rows deleted
      if ([indexPathes count] > 0) {
         [tableView deleteRowsAtIndexPaths:indexPathes withRowAnimation:UITableViewRowAnimationTop];
      }
      
      CellViewControllerForLabelAndSwitch *linkedCell = cellViewController.linkedCell;
      
      if (linkedCell != nil) {
         NSMutableArray *anotherIndexPathes = [[NSMutableArray alloc] init];
         if (linkedCell.hidden == YES) {
            linkedCell.hidden = NO;
            // Rebuild indexPath attribute pour all Cells below the current
            [self updateIndexPathForSection:cellViewController.indexPath.section 
                                    fromRow:0];
            [anotherIndexPathes addObject:linkedCell.indexPath];
         }
         
         // Animate new rows deleted
         if ([anotherIndexPathes count] > 0) {
            [tableView insertRowsAtIndexPaths:anotherIndexPathes withRowAnimation:UITableViewRowAnimationBottom];
            
            
         }
      }
   }

}

#pragma mark -
#pragma mark Implementation of protocol UICellViewForLabelAndTextFieldDelegate

-(void)cellViewController:(CellViewControllerForLabelAndTextField*)cellViewController 
  textFieldEditingChanged:(UITextField*)theTextField {
   [self checkValidityAndUpdateButtonDoneState];
}

#pragma mark -
#pragma mark Implementation of protocol DateAndTimeSelectionDelegate

-(void)dateSelectionFromDateAndTimeController:(NSDate *)theDate withIdentifier:(NSUInteger)identifier {
   NSPredicate * predicate = [NSPredicate predicateWithFormat:@"hidden == NO"];
   
   for (NSArray *array in [sections allValues]){
      for (CustomCellViewController *cellCtrl in [array filteredArrayUsingPredicate:predicate]) {
         if( cellCtrl.identifier == identifier && [cellCtrl isKindOfClass:[CellViewControllerForThreeLabels class]] ) {
            CellViewControllerForThreeLabels *cellCtrl3Labels = (CellViewControllerForThreeLabels*)cellCtrl;
            cellCtrl3Labels.mainValueText = [NSDateFormatter localizedStringFromDate:theDate 
                                                                           dateStyle:NSDateFormatterLongStyle 
                                                                           timeStyle:NSDateFormatterNoStyle];
            cellCtrl3Labels.extendedValueText = [NSDateFormatter localizedStringFromDate:theDate 
                                                                               dateStyle:NSDateFormatterNoStyle 
                                                                               timeStyle:NSDateFormatterShortStyle];
            cellCtrl3Labels.value = theDate;
            [tableView reloadData];
         }
      }
   }
}

#pragma mark -
#pragma mark Implementation of protocol CategoriesSelectionDelegate

- (void)categoriesViewController:(CategoriesViewController *)categoryViewCtrl 
               didSelectCategory:(TaskCategory *)theCategory 
                  withIdentifier:(NSUInteger)identifier {
   NSPredicate * predicate = [NSPredicate predicateWithFormat:@"hidden == NO"];
   [navController popViewControllerAnimated:YES];
   
   for (NSArray *array in [sections allValues]){
      for (CustomCellViewController *cellCtrl in [array filteredArrayUsingPredicate:predicate]) {
         if( cellCtrl.identifier == identifier && [cellCtrl isKindOfClass:[CellViewControllerForTwoLabels class]] ) {
            CellViewControllerForTwoLabels *cellCtrl2Labels = (CellViewControllerForTwoLabels*)cellCtrl;
            cellCtrl2Labels.valueText = theCategory.name;
            
            if (cellCtrl2Labels.linkedCell) {
               cellCtrl2Labels.linkedCell.hidden = NO;
            }
            [tableView reloadData];
         }
      }
   }
}

#pragma mark -
#pragma mark Actions

- (void)doneButtonPressed {
   //TODO : To complete
}

#pragma mark -
#pragma mark Custom Methods

- (NSDate *)getMaximumDate {
   NSDate *maximumDate = nil;
   
   if ( _endDateCellViewCtrl && _endDateCellViewCtrl.hidden == NO) {
      maximumDate = _endDateCellViewCtrl.value;
   }   
   else if (_endDateEstimatedCellViewCtrl && _endDateEstimatedCellViewCtrl.hidden == NO) {
      maximumDate = _endDateEstimatedCellViewCtrl.value;
   }
   
   return maximumDate;
}

#pragma mark Private Methods

- (void)resignFirstResponderForAllControls {
   for (NSArray *array in [sections allValues]){
      for (CustomCellViewController *cellCtrl in array) {
         [cellCtrl resignFirstResponderForAllControls];
      }
   }
}

- (BOOL)checkValidityAndUpdateButtonDoneState {
   BOOL validity = YES;
   NSPredicate * predicate = [NSPredicate predicateWithFormat:@"hidden == NO"];
   
   for (NSArray *array in [sections allValues]){
      for (CustomCellViewController *cellCtrl in [array filteredArrayUsingPredicate:predicate]) {
         if( [cellCtrl isKindOfClass:[CellViewControllerForLabelAndTextField class]] )
            validity = validity && 
            [self checkValidityForLabelAndTextFieldCell:(CellViewControllerForLabelAndTextField *)cellCtrl];
         else if([cellCtrl isKindOfClass:[CellViewControllerForTwoLabels class]])
            validity = validity && 
            [self checkValidityForTwoLabelsCell:(CellViewControllerForTwoLabels *)cellCtrl];
      }
   }
   
   if (validity) {
      doneButton.enabled = validity;
   }
   
   return validity;
}

- (BOOL)checkValidityForLabelAndTextFieldCell:(CellViewControllerForLabelAndTextField *)cellCtrl {
   if (cellCtrl.identifier == kCellIdTaskName && [cellCtrl.valueText length] == 0) {
      return NO;
   }
   return YES;
}

- (BOOL)checkValidityForTwoLabelsCell:(CellViewControllerForTwoLabels*)cellCtrl {
   if (cellCtrl.value)
      return YES;
   return NO;
}


- (void)updateIndexPathForSection:(NSUInteger)section {
   [self updateIndexPathForSection:section fromRow:0];
}


- (void)updateIndexPathForSection:(NSUInteger)section fromRow:(NSUInteger)theRow {
   NSPredicate * predicate = [NSPredicate predicateWithFormat:@"hidden == NO"];
   NSArray *newRows = [[sections valueForKey:[sectionNames objectAtIndex:section]] 
                      filteredArrayUsingPredicate:predicate];
   NSUInteger rowCount = [newRows count];
   
   for (NSUInteger row = theRow; row < rowCount; row++) {
      CustomCellViewController *oneCellViewCtrl = [newRows objectAtIndex:row];
      oneCellViewCtrl.indexPath = [NSIndexPath indexPathForRow:row 
                                                     inSection:section];
   }   
}



@end
